/* 
 * Handles Broadcasts page
 * 
 * @author Francis
 */


var Broadcasts = {

    inbox_attrs: {
        reply_row: null
    },
    
    outbox_attrs: {
        
    },

    init: function() {
        this.bindNavigation();
        this.bindBroadcastFields();
        this.bindInboxButtons();
    },
    
    bindNavigation: function() {
        $(".shortcuts .shortcut").click(function() {
            //$(".main-widget").hide();
            $(".shortcuts .shortcut").removeClass("active");
            
            //$( $(this).attr("href") ).show('slow');
            $(this).addClass("active");
        });
    },
    
    bindBroadcastFields: function() {
        var editted_row = null;
        
        $(".broadcast textarea").keyup(function() {
            var chars = $(this).val().length;
            var total = 140;
            var remaining = total - chars;
             
            $(".broadcast h4#characters_left").html(remaining + " Characters Left");
        }).keydown(function(e) {
            var str = String.fromCharCode(e.keyCode);
            if( $(this).val().length >= 140 && /[a-zA-Z0-9-_ +]/.test(str) ) {
                return false;
            }
             
            return true;
        });
         
        $(".broadcast button").click(function() {
            $(".broadcast :input").attr("disabled", "disabled");
            var message = $(".broadcast textarea").val();
             
            if( editted_row != null ) {
                editted_row.find(".msg").html(message);
                
                setTimeout(function() {
                    editted_row = null;
                }, 1000);
                
                Broadcasts.setupBroadcast(message, editted_row);
            }
             
            else {
                // create row in the results table
                var message_row = $("<tr />");
                message_row.append( $("<td />").html("<input type='checkbox' value='' class='simple_form' />") );
                message_row.append( $("<td class='msg' />").html(message) );
                message_row.append( $("<td />").attr('align', 'center').html("Pending") );
                message_row.append( $("<td />").css('text-align', 'center').html("<a href='#' class='btn btn-small edit_btn'>Edit</a> &nbsp; <a href='#' class='btn btn-small delete_btn'>Delete</a>") );

                $(".recent_broadcasts table tbody").prepend( message_row );
                //$(".simple_form").uniform(); 
                
                Broadcasts.setupBroadcast(message, message_row);
            }
              
             
            $(".broadcast :input").removeAttr("disabled");
            $(".broadcast textarea").val("").keyup();
        });
         
        $(".recent_broadcasts .edit_btn").live('click', function(e) {
            e.preventDefault();
            
            var msg = $(this).parents("tr").find(".msg").html();
            editted_row = $(this).parents("tr");
             
            $(".broadcast textarea").val(msg).get(0).scrollIntoView();
        });
        
        $(".recent_broadcasts .delete_btn").live('click', function(e) {
            e.preventDefault();
            
            var row = $(this).parents("tr");
             
            if( confirm("Delete Pending Broadcast?") ) {
                //row.remove();
                Broadcasts.deleteOutboxMessage(row);
            }
        });
        
        $(".checkall").change(function() {
            var checkboxes = $(this).parents("table").find("tbody input[type=checkbox]");
            
            $(this).is(":checked") ? checkboxes.attr("checked", "checked") : checkboxes.removeAttr("checked");            
        });
    },
    
    bindGeneralFields: function() {
        
    },
    
    bindInboxButtons: function() {
        $("#reply_dialog").dialog({
            title: "Reply Message To Sender",
            width: 600,
            autoOpen: false,
            open: function() {
                $(this).parents(".ui-dialog").find("button").addClass("btn");
            },
            buttons: {
                'Reply': function() {
                    var form = $("#reply_dialog form")[0];
                    if( form.checkValidity && !form.checkValidity() ) {
                        return;
                    }
                    
                    Broadcasts.replyInboxMessage();
                    $(this).dialog('close');
                },
                'Cancel': function() {
                    $(this).dialog('close');
                }
            }
        });
        
        $("#inbox_delete_conf").dialog({
            title: "Delete Confirmation",
            width: 400,
            autoOpen: false,
            open: function() {
                $(this).parents(".ui-dialog").find("button").addClass("btn");
            },
            buttons: {
                'Delete': function() {
                    Broadcasts.deleteInboxMessage();
                    $(this).dialog('close');
                },
                'Cancel': function() {
                    $(this).dialog('close');
                }
            }
        });
        
        $("#inbox .reply_btn").live('click', function() {
            $("#reply_dialog form")[0].reset();
            
            var $message = $(this).parents("td").siblings(".message");
            Broadcasts.inbox_attrs.reply_row = $(this).parents("tr");
            
            $("#reply_dialog #subscriber_message").html( $message.html() );
            $("#reply_dialog #number").val( $message.data('number') );
            
            $("#reply_dialog").dialog('open');
        });
        
        $("#inbox .delete_btn").live('click', function() {
            $("#inbox_delete_conf").dialog('open');
            
            Broadcasts.inbox_attrs.delete_row = $(this).parents("tr");
        });
    },
    
    setupBroadcast: function(message, message_row) {
        var url = $(".broadcast button").data('url');
        var query = {message: message, keyword_id:$("#current-keyword").attr('data-id')};
        
        if( message_row.data('id') != null ) {
            query.id = message_row.data('id');
        }
        
        $.post(url, query, function(data) {
            message_row.data('id', data.BroadcasterOutbox.id);
        }, 'json');
    },
    
    replyInboxMessage: function() {
        Broadcasts.inbox_attrs.reply_row.addClass("replied");
        
        var reply_btn = Broadcasts.inbox_attrs.reply_row.find(".reply_btn");
            reply_btn.attr("disabled", true);
        
        var url = reply_btn.data('url');
        var query = $("#reply_dialog form").serialize();
        
        $.post(url, query, function() {
            
        });
    },
    
    deleteInboxMessage: function() {
        var delete_btn = Broadcasts.inbox_attrs.delete_row.find(".delete_btn");
        
        var url = delete_btn.data('url');
        
        $.post(url, function() {
            Broadcasts.inbox_attrs.delete_row.hide('slow', function() {
                Broadcasts.inbox_attrs.delete_row.remove();
                Broadcasts.inbox_attrs.delete_row = null;
            });
        });
    },
    
    deleteOutboxMessage: function(message_row) {
        var url = message_row.find(".delete_btn").attr('href');
        
        if( url == "#" ) {
            url = $(".recent_broadcasts #delete_url").val() + "/" + message_row.data('id');
        }
        
        $.post(url, function() {
            message_row.remove();
        });
    }
};

$(document).ready(function() {  
    Broadcasts.init();
});